package com.atguigu.system.controller;

import com.atguigu.common.result.Result;
import com.atguigu.common.utils.JwtHelper;
import com.atguigu.common.utils.MD5;
import com.atguigu.model.system.SysUser;
import com.atguigu.model.vo.LoginVo;
import com.atguigu.system.handler.GuiguException;
import com.atguigu.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "用户模块")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {
    @Autowired
    private SysUserService sysUserService;

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo) {
        Map<String, Object> map = new HashMap<>();
        SysUser user = sysUserService.getUserInfoByUserName(loginVo.getUsername());
        if (user == null) {
            throw new GuiguException(20001, "用户不存在");
        }
        if (!user.getPassword().equals(MD5.encrypt(loginVo.getPassword()))) {
            throw new GuiguException(20001, "密码错误");
        }
        if (user.getStatus().intValue() == 0) {
            throw new GuiguException(20001, "用户被禁用");
        }
        //根据id和name生成token字符串
        String token = JwtHelper.createToken(user.getId(), user.getUsername());
        map.put("token", token);
        return Result.ok(map);
    }

    @ApiOperation("用户信息")
    @GetMapping("/info")
    public Result info(HttpServletRequest request) {
//        map.put("roles", "[admin]");
//        map.put("name", "Super Admin");
//        map.put("introduction", "I am a super administrator");
//        map.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        String token = request.getHeader("token");
        String username = JwtHelper.getUsername(token);
        Map<String, Object> map = sysUserService.getUserInfo(username);
        return Result.ok(map);
    }

    @ApiOperation("退出")
    @PostMapping("/logout")
    public Result logout() {
        return Result.ok();
    }
}
